package utils;

import book.Book;
import com.bit.utils.FileUtils;
import constant.Constant;
import java.io.IOException;
import java.time.LocalDate;

public class AnalyzingBook {
    //将系统中的书籍对象以Json的格式存储到
    public static void storeObject(Book[] books,String filename) throws IOException {
          //首先确认books数组中有效书籍的个数
        int bookCount = 0;
        for (Book book : books) {
            if (book != null) {
                bookCount++;
            }
        }

        StringBuffer sb = new StringBuffer();
        String json = null;
        for(int j = 0;j < bookCount;j++) {
            assert books[j] != null;
            json = books[j].toJson();
            sb.append(json);
            if(j != bookCount - 1) {
                sb.append("\n");
            }
        }

       //数据写入文件
        FileUtils.writeFile(sb.toString(),filename);
    }
    //从文件中的Json数据中加载出书籍对象
    public static Book[] loadObject(String filename) throws IOException{
        //从文件中读取数据
        String content = FileUtils.readFile(filename);
        if(content == null || content.isEmpty()) {
            System.out.println("文件为空！");
            return null;
        }

        //2.以换行符\n分割字符串
        String[] contents = content.split("\n");

        Book[] books = new Book[contents.length];

        for (int i = 0; i < books.length; i++) {
            books[i] = parseBookJson(contents[i]);
        }


        return books;

    }

    private static Book parseBookJson(String json) {
        //根据Json字符串构造对象
        String[] jsonArray = json.split(",");
        int bookId = Integer.parseInt(jsonArray[0]);
        String title = jsonArray[1];
        String author = jsonArray[2];
        String category = jsonArray[3];
        int publishYear = Integer.parseInt(jsonArray[4]);
        LocalDate shelfDate = LocalDate.parse(jsonArray[5]);

        String borrowResult = jsonArray[6];
        boolean isBorrowed;
        if(borrowResult.equals("未借出")) {
            isBorrowed = false;
        }else {
            isBorrowed = true;
        }

        int borrowCount = Integer.parseInt(jsonArray[7]);

        Book book = new Book(title,author,category,publishYear);
        book.setShelfDate(shelfDate);
        book.setBorrowed(isBorrowed);
        book.setBorrowCount(borrowCount);

        return book;
    }

    public static void main1(String[] args) throws IOException{
        Book[] books = new Book[4];
        books[0] = new Book("Java","gaobo","编程",2020);
        books[1] = new Book("mysql","lisi","编程",2019);
        books[2] = new Book("php","gaobo","编程",2018);
        books[3] = new Book("西游记","吴承恩","小说",1649);

        storeObject(books,Constant.all_books_file);

    }

    public static void main(String[] args) throws IOException{
        Book[] books = loadObject(Constant.all_books_file);
        assert books != null;
        for (Book book : books) {
            System.out.println(book);
        }
    }
}
